package com.naiterui.ehp.bs.patient.config;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.naiterui.ehp.bs.wechat.protocol.msg.template.IndustryConfig;
import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateAdd;
import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateAddResult;
import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateInfo;
import com.naiterui.ehp.bs.wechat.protocol.msg.template.TemplateList;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhoupeipei
 * @date 2019-06-19 17:12
 * @since 1.0.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "template")
public class TemplateConfig implements InitializingBean {

    private List<TemplateProperties> template;
    private final IAccessTokenService accessTokenService;

    /**
     * 模板配置集合   key:label;value:模板配置属性
     * @return
     */
    public Map<String, TemplateProperties> templateMap() {
        return Optional.ofNullable(template)
                       .map(t -> t.stream().collect(Collectors.toMap(TemplateProperties::getLabel, Function.identity())))
                       .orElse(new HashMap<>());
    }

    public List<TemplateProperties> getTemplate() {
        return template;
    }

    public void setTemplate(List<TemplateProperties> template) {
        this.template = template;
    }

    @Override
    public void afterPropertiesSet() {

        try {
            String industryResult = WeChatApiUtil.getIndustry(accessTokenService.accessToken());
            if (!(industryResult.contains("互联网|电子商务") && industryResult.contains("保健与卫生"))) {
                WeChatApiUtil.setIndustry(accessTokenService.accessToken(), IndustryConfig.builder().industry_id1("1").industry_id2("24").build());
            }

            TemplateList templateList = WeChatApiUtil.getTemplate(accessTokenService.accessToken());
            Map<String,String> templateMap = Optional.ofNullable(templateList.getTemplate_list())
                .map(list->list.stream().collect(Collectors.toMap(TemplateInfo::getTitle, TemplateInfo::getTemplate_id))).orElse(Collections.emptyMap());
            template.forEach(t -> {
                String templateId = templateMap.get(t.getTitle());
                if (templateId == null) {
                    TemplateAdd templateAdd = TemplateAdd.builder().template_id_short(t.getTId()).build();
                    TemplateAddResult result = WeChatApiUtil.setTemplate(accessTokenService.accessToken(), templateAdd);
                    log.info("TemplateConfig Initializing AddTemplate ; request={} ,result={}", templateAdd, result);
                    templateId = result.getTemplate_id();
                    templateMap.put(t.getTitle(), templateId);
                }
                t.setTemplateId(templateId);
            });
            log.info("TemplateConfig Initializing Result " + JSONUtil.toJsonStr(template));

        } catch (Exception e) {
            log.warn("TemplateConfig Initializing ERROR " , e);
        }

    }
}
